package com.example.kt_temp.ui.viewmodel

import android.content.Context
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.kt_temp.model.UserInfoManager
import com.example.kt_temp.model.entity.UserInfoEntity
import com.example.kt_temp.model.service.UserService
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import java.security.MessageDigest

class UserViewModel(context:Context):ViewModel() {

    private val userInfoManager = UserInfoManager(context)
    private val userService = UserService.instance()

    var userName by mutableStateOf("")

    var passWord by mutableStateOf ("")

    var userInfo:UserInfoEntity?=null
         private set

    init {
        viewModelScope.launch {
            //拿到userName 不为空创建实体 并初始化
            val userName = userInfoManager.userName.firstOrNull()
            userInfo = if(userName?.isNotEmpty() == true){
                UserInfoEntity(userName)
            }else{
                null
            }
        }
    }

    //是否已登录
    val logged:Boolean
        get(){
            return userInfo !=null
        }

    //正在登录
    var loading by mutableStateOf(false)
        private set

    //登录失败
    var error by mutableStateOf("")
        private set

    //登录操作
    suspend fun login(onClose:()->Unit){
        error = ""
        loading = true
        val res = userService.sigIn(userName,md5(passWord))
        if(res.code==0 &&res.data!=null){
            userInfo = res.data
            userInfoManager.save(userName)
            onClose()

        }else{
            //失败
//            Log.i("===","$msg")
            error = res.message
        }
        loading = false
    }

    fun md5(content: String): String {
        val hash = MessageDigest.getInstance("MD5").digest(content.toByteArray())
        val hex = StringBuilder(hash.size * 2)
        for (b in hash) {
            var str = Integer.toHexString(b.toInt())
            if (b < 0x10) {
                str = "0$str"
            }
            hex.append(str.substring(str.length - 2))
        }
        return hex.toString()
    }

    //退出登录操作
    fun clear(){
        viewModelScope.launch {
            userInfoManager.clear() //清除本地数据存储
            userInfo = null //置空内存数据
        }
    }

}